package dateBase;


import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import site.SiteBean;

public class SiteDBHelper extends SQLiteOpenHelper {
    private static final String DB_NAME = "sql.db";
    private static final int DB_VERSION = 1;
    private static final String TABLE_SITE_NAME = "site";
    private static SiteDBHelper mHelper = null;//只生成一个构造数据库的实例
    private SQLiteDatabase mRDB = null;//读链接
    private SQLiteDatabase mWDB = null;//写链接

    private SiteDBHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }


    public static SiteDBHelper getInstance(Context context) {
        if (mHelper == null) {
            mHelper = new SiteDBHelper(context);
        }
        return mHelper;
    }

    //打开数据库的读链接
    public SQLiteDatabase openReadLink() {
        if (mRDB == null || !mRDB.isOpen()) {
            mRDB = mHelper.getReadableDatabase();
        }
        return mRDB;
    }

    //打开数据库的写链接
    public SQLiteDatabase openWriteLink() {
        if (mWDB == null || !mWDB.isOpen()) {
            mWDB = mHelper.getWritableDatabase();
        }
        return mWDB;
    }

    public void closeLink() {

        if (mRDB != null && mRDB.isOpen()) {
            mRDB.close();
            mRDB = null;
        }

        if (mWDB != null && mWDB.isOpen()) {
            mWDB.close();
            mWDB = null;
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_SITE_NAME + " (" +
                "sno char(9) PRIMARY KEY NOT NULL COLLATE NOCASE," +
                "sname char(25) NOT NULL COLLATE NOCASE," +
                "scapacity char(10) COLLATE NOCASE ," +
                "stypes char(20) COLLATE NOCASE," +
                "saddress char(20) COLLATE NOCASE);";

        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }


    //插入
    public long insert(SiteBean site) {
        ContentValues values = new ContentValues();//用键值对形式存储
        values.put("sno", site.getSno());
        values.put("sname", site.getSname());
        values.put("scapacity", site.getScapacity());
        values.put("stypes", site.getStypes());
        values.put("saddress", site.getSaddress());
        Log.v("MainActivity", site.getSno());
        return mWDB.insert(TABLE_SITE_NAME, null, values);//返回插入的行号，失败返回-1
        //第二个参数是为了防止values均为空，报错的情况
    }


}
